package com.ns.sbs.oauth.my;

import com.ns.core.annotations.ReqLog;
import com.ns.core.utils.StpUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.core.utils.sg.ResultOk;
import com.ns.sbs.oauth.acc.bo.AccBO;
import com.ns.sbs.oauth.acc.entry.Account;
import com.ns.sbs.oauth.acc.service.IAccountService;
import com.ns.sbs.oauth.acc.vo.AccCompleteVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 我的模块业务相关操作
 *
 * @author lw
 */
@RestController
@RequestMapping("/sso/my/")
@RequiredArgsConstructor
@CrossOrigin
public class SsoMyController {

    private final IAccountService accountService;

    /**
     * 改
     *
     * @param bo 参数
     */
    @PostMapping("update")
    @ReqLog(module = "我的模块", name = "改个人信息", isRecordFlag = true)
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public ResultOk updateAll(@RequestBody AccBO bo) {
        // 当前手机号获取用户
        Account account = new Account();
        BeanUtils.copyProperties(bo, account);
        AccCompleteVO acc = accountService.getAccByPhone(bo.getPhone());
        if (Objects.nonNull(acc)) {
            if (Objects.equals(acc.getId(), bo.getId())) {
                accountService.updateById(account);
            } else {
                throw new ResultError(String.format("该手机号%s已被使用！", account.getPhone()));
            }
        } else {
            accountService.updateById(account);
        }
        return ResultOk.getSuccessData(account.getId());
    }

    /**
     * 查
     */
    @GetMapping("getById")
    @ReqLog(module = "我的模块", name = "查")
    public ResultOk getById() {
        return ResultOk.getSuccessData(accountService.getAccById(StpUtil.getLoginUserId(), StpUtil.getSid()));
    }
}
